package com.yunduansing.core.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yunduansing.core.commons.DbCommon;
import com.yunduansing.core.model.AccountModel;
import com.yunduansing.core.model.TemplateModel;
import com.yunduansing.core.service.TemplateService;
import com.yunduansing.core.service.TemplateTypeService;
import com.yunduansing.core.utils.CommonUtil;

@Controller
@RequestMapping("/manager/template")
public class TemplateController {
	@Autowired
	private TemplateService service;
	@Autowired
	private TemplateTypeService templateTypeService;
	
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public ModelAndView index(HttpSession session){
		ModelAndView view=new ModelAndView();
		view.setViewName("/beetl/template/index");
		System.out.println(((AccountModel)session.getAttribute("CurrentUser")).getName());
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value="/page",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String pagination(DbCommon.Grid grid,@RequestParam(value="keys",required=false) Map<String,Object> keys){
		return CommonUtil.toJsonWithGson(service.pagination(grid, keys));
	}
	
	@RequestMapping(value="/detail")
	public ModelAndView detail(Model model,@RequestParam(value="id",required=false) Integer id){
		ModelAndView view=new ModelAndView();
		view.setViewName("/beetl/template/detail");
		TemplateModel template;
		if(id==null)
			template=new TemplateModel();
		else
			template=service.getById(id);
		System.out.println(template.getType_id());
		model.addAttribute("model",template);
		model.addAttribute("typeList", templateTypeService.getAll());
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value="/buttonlist",method=RequestMethod.GET,produces="application/json;charset=utf-8")
	public String getButtonsByTemplateId(int templateId){
		return CommonUtil.toJsonWithGson(service.getButtonsByTemplateId(templateId));
	}
	
	@ResponseBody
	@RequestMapping(value="/save",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String save(TemplateModel model){
		return CommonUtil.toJsonWithGson(service.save(model));
	}
	
	@ResponseBody
	@RequestMapping(value="/delete",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String delete(@RequestParam("ids[]") List<Integer> ids){
		return CommonUtil.toJsonWithGson(service.delete(ids));
	}
}
